package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file/")
@Tag(name = "04-文件上传接口")
public class UploadController {

    @PostMapping("upload")
    @Operation(summary = "上传接口")
    public JsonResult upload(MultipartFile file) throws IOException {
        log.debug("开始处理【上传】的请求");
        //获取原文件名
        String fileName = file.getOriginalFilename();
        //获取文件的扩展名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成唯一的标识
        fileName = UUID.randomUUID()+suffix;
        //处理路径
        String dirPath="d:/filesPicture";
        SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath=sdf.format(new Date());
        //创建目录
        File files=new File(dirPath+datePath);
        if(!files.exists()){
            files.mkdirs();
        }
        //保存文件
        String path=dirPath+datePath+fileName;
        log.debug("保存文件的路径：{}",path);
        file.transferTo(new File(path));
        log.debug("保存文件成功！");

        return JsonResult.ok(datePath+fileName);
    }
}
